﻿using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using GalaSoft.MvvmLight.Messaging;
using AzureTracer.ViewModels;
using System.Windows.Navigation;
using Serialization;

namespace AzureTracer.Views
{
    public partial class LoginPage : PhoneApplicationPage
    {
        bool _isNewPageInstance = false;

        public LoginPage()
        {
            InitializeComponent();
            this.Loaded += OnLoaded;
            this.Unloaded += OnUnloaded;
            _isNewPageInstance = true;                      
        }

        void OnLoaded(object sender, RoutedEventArgs e)
        {
            ApplicationBar.MatchOverriddenTheme();
            DataStateManagerEx.ResetAll();
            Messenger.Default.Register<string>(this, LoginViewModel.WARNINGDIALOG_MESSAGE,
              (message) => MessageBox.Show(message));
        }

        void OnUnloaded(object sender, RoutedEventArgs e)
        {
            Messenger.Default.Unregister<string>(this, LoginViewModel.WARNINGDIALOG_MESSAGE);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode != NavigationMode.Back)            
                State["ViewModel"] = SilverlightSerializer.Serialize(this.DataContext);            
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {           
            if (!_isNewPageInstance) return;

            if (State.Count != 0)
                DataContext = SilverlightSerializer.Deserialize(State["ViewModel"] as byte[]);            
            State.Clear();

            _isNewPageInstance = false;
        }

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            ClearBackEntries();
            base.OnBackKeyPress(e);
        }

        private void ClearBackEntries()
        {
            while (NavigationService.BackStack != null & NavigationService.BackStack.Count() > 0)
                NavigationService.RemoveBackEntry();
        }

    }
}